package com.yunfeng.supercall.activity;

import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.anim;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.LayoutParams;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lin.activity.PersonalDetailCardActivity;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.PinterestCircleBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.FriendsDetailBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.PushManager;

/**
 * 好友详情页面
 * 
 * @author 洋
 * 
 */
public class FriendsDetailActivity extends BaseActivity {
	LinearLayout ll ;
	private SuperFriendsBean mSuperFriends;
	/** 所有好友 */
	List<SuperFriendsBean> mList;
	private FriendsDetailBean mFriendsDetail;
	/** 不看我和我不看他两个switch控件 */
	private SwitchCompat mSwitchCompatLookHe, mSwitchCompatLookMe;
	/** 最近分享图片列表 */
	private RecyclerView mRecyclerView;
	private List<String> mRecentShare;
	DisplayImageOptions options;
	Session mSession;
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mSession = Session.getSession();
		setContentView(R.layout.activity_friends_detail);
		Session mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		
		
		options = new DisplayImageOptions.Builder()
		.displayer(new PinterestCircleBitmapDisplayer(getResources().getDimensionPixelSize(R.dimen.corners_avatar)))
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();

		buttonDelete = (Button) findViewById(R.id.btn_delete);
		imageViewSex = (ImageView) findViewById(R.id.imageview_sex);
		mList = (List<SuperFriendsBean>) ManagerFactory.createManager(
				SuperFriendsBean.class).getList();
		mSuperFriends = getIntent().getParcelableExtra(KEY_DATA);
		userBean = BaseActivity.getUser(getApplicationContext());
		/*(返回值:1=超友,2=关注,3=粉丝,0=陌生人)*/
		mSession.checkRelation(getApplicationContext(), userBean.getUserid(), mSuperFriends.getUserid(), new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer data) {
				// TODO Auto-generated method stub
				if(data == 0) {
					buttonDelete.setVisibility(View.INVISIBLE);
				}
			}
		});
		boolean show = getIntent().getBooleanExtra(KEY_DONT_SHOW_NUMBER, false);
		if (show) {
			findView(R.id.phone).setVisibility(View.INVISIBLE);
		}
		setTitleBar(R.string.user_detail);
		// if (mList.contains(mSuperFriends)) {
		// findView(R.id.friends_button_area).setVisibility(View.VISIBLE);
		// findView(R.id.friends_more_area).setVisibility(View.VISIBLE);
		// findView(R.id.add_friends_area).setVisibility(View.GONE);
		// loadFriendsDetail();
		// } else {
		// findView(R.id.friends_button_area).setVisibility(View.GONE);
		// }
		if (mSuperFriends.getType() == SuperFriendsBean.TYPE_ENTERPRISE) {
			findView(R.id.add_friend).setVisibility(View.GONE);
			setTitleBar(R.string.enterprise_detail);
			boolean b = getIntent().getBooleanExtra(KEY_IS_FRIEND, false);
			if (b) {
				findView(R.id.guanzhu).setVisibility(View.GONE);
			}
		}
		LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
		ll.setOnClickListener(new android.view.View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(FriendsDetailActivity.this, PersonalDetailCardActivity.class);
				intent.putExtra(KEY_DATA, mSuperFriends);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		
		if(mSuperFriends.getSex() == 1) {
			imageViewSex.setImageDrawable(getResources().getDrawable(R.drawable.ic_male));	
		}else if(mSuperFriends.getSex() == 2) {
			imageViewSex.setImageDrawable(getResources().getDrawable(R.drawable.ic_female));	
		}

		ContactsBaseBean.setupSingleLineContactsView(getWindow().getDecorView(),
				mSuperFriends);
		// setTextViewText(R.id.nick_name, mSuperFriends.getNick_name());
		setTextViewText(R.id.addr,
				getString(R.string.area, mSuperFriends.getAddress()));
		setTextViewText(R.id.sign, mSuperFriends.getNote());
		setTextViewText(R.id.phone, mSuperFriends.getSuperNumber());
		// setTextViewText(R.id.level,
		// MainActivity.LEVEL_MAPS.get(mSuperFriends.getLevel() + ""));
		setTextViewText(R.id.beizhu, mSuperFriends.getNick_name());
		mSwitchCompatLookHe = findView(R.id.look_he);
		mSwitchCompatLookMe = findView(R.id.look_me);
		mSwitchCompatLookMe
		.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				changeState(STATE_LOOKME, buttonView);
			}
		});
		mSwitchCompatLookHe
		.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				changeState(STATE_LOOKHE, buttonView);
			}
		});
		/*AppContext.displayImgWithDefault((ImageView) findView(R.id.iv),
				mSuperFriends.getPhoto());*/
		ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mSuperFriends.getPhoto(), (ImageView) findView(R.id.iv), options);
		mRecyclerView = findView(R.id.recycler_view);
		LinearLayoutManager layoutManager = new LinearLayoutManager(
				getActivity());
		layoutManager.setOrientation(RecyclerView.HORIZONTAL);
		mRecyclerView.setLayoutManager(layoutManager);
		isFriend();

	}

	private void loadCallTime() {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		try {
			json.put("i_userid", mSuperFriends.getUserid());
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_USER_CALL_TIME, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(data.substring(1,
							data.length() - 1));
					setTextViewText(
							R.id.online_day,
							getResources().getQuantityString(
									R.plurals.days,
									json.getInt("onlineday"),
									json.getInt("onlineday")));
					// int sec = json.getInt("calltime");
					// if (sec < 60) {
					// setTextViewText(R.id.call_time, sec + "秒");
					// } else {
					// setTextViewText(R.id.call_time, sec / 60 + "分"
					// + sec % 60 + "秒");
					// }

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
	}

	/**
	 * 查询是否好友关系
	 */
	private void isFriend() {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_otherid", mSuperFriends.getUserid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_CHECK_IS_FRIENDS, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(data.substring(1,
							data.length() - 1));
					int isFriend = json.getInt("isfriend");
					if (isFriend == 1) {// 是好友
						findView(R.id.friends_button_area).setVisibility(
								View.VISIBLE);
						findView(R.id.friends_more_area).setVisibility(
								View.VISIBLE);
						findView(R.id.add_friends_area)
						.setVisibility(View.GONE);
						loadFriendsDetail();
						loadCallTime();
					} else {// 不是好友
						if (mList.contains(mSuperFriends)) {// 但是粉丝或者关注的人
							findView(R.id.fans_add_friends_area).setVisibility(
									View.VISIBLE);
							findView(R.id.add_friends_area).setVisibility(
									View.GONE);
							findView(R.id.name_area).setVisibility(View.GONE);
							loadFriendsDetail();
							loadCallTime();
						} else {
							findView(R.id.friends_button_area).setVisibility(
									View.GONE);
						}

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 查看分享
	 * 
	 * @param v
	 */
	public void seeShare(View v) {
		startActivity(new Intent(this, FriendShareListActivity.class).putExtra(
				KEY_DATA, mSuperFriends.getUserid()));
	}

	public static final int STATE_LOOKHE = 1;
	public static final int STATE_LOOKME = 2;
	public static final int STATE_BLACK = 3;
	private ImageView imageViewSex;
	private Button buttonDelete;
	private UserBean userBean;

	/**
	 * 加入黑名单
	 * 
	 * @param v
	 */
	public void addToBlack(View v) {
		changeState(3, v);
		SwitchCompat compat = (SwitchCompat) v;
		mSession.setFriendState(getApplicationContext(), mSession.getmUserBean().getUserid() + "", mSuperFriends.getUserid() + "", "" + (compat.isChecked() ? 1 : 0), new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer result) {
				// TODO Auto-generated method stub
				if(result == 1) {
					
				}
			}
			
		});
	}

	/**
	 * 不看他的分享
	 * 
	 * @param v
	 */
	public void dontSeehe(View v) {
		SwitchCompat compat = (SwitchCompat) v;

		mSession.setShareStateUser(getApplicationContext(), mSession.getmUserBean().getUserid() + "", mSuperFriends.getUserid() + "", "" + (compat.isChecked() ? 1 : 0), new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer result) {
				// TODO Auto-generated method stub
				if(result == 1) {
					
				}
			}
			
		});
		changeState(1, v);
	}

	/**
	 * 不让他看我的分享
	 * 
	 * @param v
	 */
	public void dontLetHeSee(View v) {
		SwitchCompat compat = (SwitchCompat) v;

		mSession.setShareStateUser(getApplicationContext(), mSession.getmUserBean().getUserid() + "", mSuperFriends.getUserid() + "", "" + (compat.isChecked() ? 1 : 0), new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer result) {
				// TODO Auto-generated method stub
				if(result == 1) {
					
				}
			}
			
		});
		changeState(2, v);
	}

	/**
	 * 修改分享状态
	 * 
	 * @param type
	 * @param v
	 */
	private void changeState(int type, View v) {
		SwitchCompat compat = (SwitchCompat) v;
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_otherid", mSuperFriends.getUserid());
			json.put("i_type", type);
			json.put("i_state", compat.isChecked() ? 1 : 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_CHANGE_STATE, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {

			}

			@Override
			public void onReceiveData(String data, String msg) {
			}
		});

	}

	/**
	 * 修改备注
	 * 
	 * @param v
	 */
	public void changeBeizhu(View v) {
		final EditText mEditText = new EditText(this);
		mEditText.setHint(getString(R.string.input_remark));
		Builder mBuilder = new Builder(this);
		mBuilder.setTitle(R.string.change_remark);
		mBuilder.setNegativeButton(android.R.string.cancel, null);
		mBuilder.setView(mEditText);
		mBuilder.setPositiveButton(android.R.string.ok, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				final String text = mEditText.getText().toString();
				if (!TextUtils.isEmpty(text)) {
					JSONObject json = getBaseParams(getActivity());
					try {
						json.put("i_friendid", mSuperFriends.getUserid());
						json.put("i_note", text);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					showProgressDialog(R.string.editing);
					mHttpClient.post(FUNCTION_CHANGE_FRIENDS_NOTE, json,
							new MyAjaxCallBack() {

						@Override
						public void onReceiveError(String msg,
								String errorCode) {
							// TODO Auto-generated method stub
							showToast(msg);
							cancelProgressDialog();
						}

						@Override
						public void onReceiveData(String data,
								String msg) {
							// TODO Auto-generated method stub
							showToast(R.string.edit_success);
							cancelProgressDialog();
							setTextViewText(R.id.beizhu, text);
							List<SuperFriendsBean> friends = ManagerFactory
									.createManager(SuperFriendsBean.class)
									.getList();
							for (SuperFriendsBean superFriends : friends) {
								if (superFriends.getUserid() == mSuperFriends
										.getUserid()) {
									superFriends.setNick_name(text);
								}
							}
						}
					});
				}
			}
		});
		mBuilder.show();
	}

	/**
	 * 加载好友详情
	 */
	private void loadFriendsDetail() {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put(KEY_FRIEND_ID, mSuperFriends.getUserid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_FRIEND_DETAIL, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				mFriendsDetail = JsonUtils.parse(
						data.substring(1, data.length() - 1),
						FriendsDetailBean.class);
				if (mFriendsDetail == null) {
					return;
				}
				mSwitchCompatLookHe.setChecked(mFriendsDetail
						.getLookhe() != 0);
				mSwitchCompatLookMe.setChecked(mFriendsDetail
						.getLookme() != 0);
				if (mFriendsDetail.getImg() != null
						&& !(mFriendsDetail.getImg().length() == 0)) {
					mRecentShare = Arrays.asList(mFriendsDetail
							.getImg().split(";"));
					mRecyclerView.setAdapter(new RecentShareAdapter());
				}
			}
		});
	}

	/**
	 * 添加为好友
	 * 
	 * @param v
	 */
	public void addToFriends(View v) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_otherid", mSuperFriends.getUserid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showProgressDialog(R.string.applying);
		mHttpClient.post(FUNCTION_ADD_FRIENDS, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				showToast(R.string.wait_for_response);
				PushManager.startPush(
						PushManager.TYPE_ADD_FRIEND,
						getString(R.string.someone_apply_for_making_friends,
								getUser(getActivity()).getNick_name()), "",
								mSuperFriends.getPhone());
				cancelProgressDialog();
			}
		});
	}

	/**
	 * 关注
	 * 
	 * @param v
	 */
	public void attention(View v) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_otherid", mSuperFriends.getUserid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showProgressDialog(R.string.applying);
		mHttpClient.post(FUNCTION_ADD_GUANZHU, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				showToast(R.string.focused);
				cancelProgressDialog();
			}
		});
	}

	/**
	 * 更改分组
	 * 
	 * @param v
	 */
	public void changeGroup(View v) {
		showToast(R.string.select_a_group);
		startActivityForResult(
				new Intent(this, FriendsGroupListActivity.class)
				.setAction(ACTION_CHANGE_GROUP),
				300);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 300) {
				if (data != null) {
					int groupId = data.getIntExtra(KEY_DATA, 0);
					changeGroup(groupId);
				}
			}
		}
	}

	/**
	 * 变更好友分组
	 * 
	 * @param id
	 *            分组的ID
	 */
	private void changeGroup(int id) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_friendid", mSuperFriends.getUserid());
			json.put("i_groupid", id);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showProgressDialog(R.string.editing);
		mHttpClient.post(FUNCTION_CHANGE_FRIENDS_GROUP, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				showToast(R.string.editing);
				cancelProgressDialog();
			}
		});

	}

	/**
	 * 删除好友
	 * 
	 * @param v
	 */
	public void delete(View v) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_friendid", mSuperFriends.getUserid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showProgressDialog(R.string.applying);
		mHttpClient.post(FUNCTION_DEL_FRIENDS, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				sendBroadcast(new Intent(ACTION_NEWFRIEND_MSG));

				showToast(R.string.delete_success);
				mList.remove(mSuperFriends);
				Intent i = new Intent();
				i.putExtra(KEY_DATA, true);
				setResult(RESULT_OK, i);
				finish();
				cancelProgressDialog();
			}
		});
	}

	public static class MyViewHolder extends ViewHolder {

		public MyViewHolder(View arg0) {
			super(arg0);
			// TODO Auto-generated constructor stub
		}

	}

	/**
	 * 好友最近分享的数据适配器
	 * 
	 * @author 洋
	 * 
	 */
	public class RecentShareAdapter extends Adapter<MyViewHolder> {

		@Override
		public int getItemCount() {
			// TODO Auto-generated method stub
			return mRecentShare.size();
		}

		@Override
		public void onBindViewHolder(MyViewHolder arg0, int arg1) {
			// TODO Auto-generated method stub
			ImageView iv = (ImageView) arg0.itemView;
			iv.setPadding(8, 8, 8, 8);
			iv.setLayoutParams(new LayoutParams(getResources()
					.getDimensionPixelSize(R.dimen.avatar_size), getResources()
					.getDimensionPixelSize(R.dimen.avatar_size)));
			AppContext.displayImgWithDefault1(iv, mRecentShare.get(arg1));
			iv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivity(new Intent(getActivity(),
							FriendShareListActivity.class).putExtra(KEY_DATA,
									mSuperFriends.getUserid()));
				}
			});
		}

		@Override
		public MyViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
			// TODO Auto-generated method stub
			ImageView mImageView = new ImageView(getActivity());
			MyViewHolder holder = new MyViewHolder(mImageView);
			return holder;
		}
	}
}
